package com.microcore.job;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.microcore.util.SpringContextUtils;

public class DynamicJob {
	
	protected Logger logger = LoggerFactory.getLogger(DynamicJob.class);

	protected void executeJob(JobExecutionContext executorContext) {
		//JobDetail中的JobDataMap是共用的,从getMergedJobDataMap获取的JobDataMap是全新的对象
        JobDataMap map = executorContext.getMergedJobDataMap();
        String className = map.getString("className");
        String methodName = map.getString("methodName");
        Object[] keys = (Object[]) map.get("sortArray");
        List<Object> tempList = new ArrayList<>();
        for (Object key : keys) {
            tempList.add(map.get(key));
        }
        Object[] params = tempList.toArray();
        try {
            //通过spring容器获取object
            Object obj = SpringContextUtils.getBean(className);
            //根据Class对象获取method方法
            Method[] methods = obj.getClass().getDeclaredMethods();
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    logger.info("*****开始执行调度，执行类路径：" + className + "， 执行方法：" + methodName);
                    method.invoke(obj, params); //执行指定的方法(methodName)
                }
            }

        } catch (Exception e) {
            logger.error("执行调度失败", e);
        }
	}
	
	
}
